<?php

//Created by Timothy Cheung

class availability_model extends CI_Model {

    var $loan_status = '';
    var $barcode = '';
    var $collection = '';
    var $location = '';
    var $sub_library = '';
    var $due_date = '';
    var $due_time = '';
    var $docnum = '';
    var $html = '';
    var $locator = '';

    function __construct() {
        parent::__construct();
    }
/*
|--------------------------------------------------------------------------
| parseAvailXML (@author : Timothy Cheung)
|--------------------------------------------------------------------------
|
| This function takes the XML returned from X-Services API as input, parses 
| and returns an availability record for the Details View module
| For information on the purpose of the variables, please check
| app/view/DetailsViewModule/AvailTabDataView.js's comments
*/
    function parseAvailXML($xmlAvail, $xml_seq, $docnum) {
        $item_datas = array();
        $seq_items = array();
        $html_str = '';
        $load = false; 
        $error = false;
        //count_total - total number of records which passed filter, or 1 for object with
        //              error tag. If count_total==0 at the end, means records exist but all 
        //              have been filtered
        $count_total = 0; 
        $item = new availability_model();
        
        //*Note: if an item has no availability records, API returns XML with <error> tag
        //checks if the XML file contains any error tag
        foreach ($xmlAvail->{'error'} as $item_data) {
            if ($item_data != null) {
                //set error to true if error tag exists
                $error = true;
            }
        }
        
        //if error tag is found, set standard values to variables and return single item
        if ($error) {
            $item->loan_status = "No Hard Copies Available";
            $item->due_date = "-";
            $item->due_time = "-";
            $item->sub_library = "-";
            $item->collection = "-";
            $item->location = "-";
            $item->barcode = "-";
            $count_total++;     //increment to 1 to pass all filtered check
            $item_datas[] = $item;
        } else {
            
            //Load each item-seq into array
            foreach ($xml_seq->{'item'} as $segItem) {
                //rec-key barcode on-hold requested
                $seq_items[(string) $segItem->barcode] = array(
                    "rec_key" => (string) $segItem->{'rec-key'},
                    "on_hold" => (string) $segItem->{'on-hold'},
                    "requested" => (string) $segItem->requested
                );
            }
            
           
            
            $count_item = 0;
            
            //for each item-data entry in avail xml
            foreach ($xmlAvail->{'item-data'} as $item_data) {
                //loop through each filter phrase in filterTerms array
                foreach ($this->config->item('filterTerms') as $filter) {
                    //if item's loan-status matches any filter phrase
                    if (strstr(strtolower($item_data->{'loan-status'}), strtolower($filter))) {
                        //set load to false and break loop
                        $load = false;
                        $item->location = (string) $item_data->location;
                        break;
                    } else {
                        //else set load to true
                        $load = true;
                    }
                }
                //if item passed filter check
                if ($load) {
                    //if the current item count is less than the load item limit
                    if ($count_item < $this->config->item('loadNum')) {
                        //parse next item from xml
                        $item = new availability_model();
                        //if loan-status is not blank,
                        if ($item_data->{'loan-status'} != "") {
                            //if the string count of the loan-status is less than or equal to 16
                            $item->loan_status = (string) $item_data->{'loan-status'};
                            
                        } else {
                            //if loan-status is blank, set default value
                            $item->loan_status = "-";
                        }
                        
                        //calls blankCheck to check if any of the fields are "", and to set default value if true
                        //else set the item data value
                        $item->due_date = $this->blankCheck($item_data->{'due-date'});
                        $item->due_time = $this->blankCheck($item_data->{'due-hour'});
                        $item->sub_library = $this->blankCheck($item_data->{'sub-library'});
                        $item->collection = $this->blankCheck($item_data->collection);
                        $item->location = $this->blankCheck($item_data->location);
                        $item->barcode = $this->blankCheck($item_data->barcode);

                        //if there is no error tag in the XML
                        //and at least one item passed filter
                        if ($item->loan_status != "No Hard Copies Available") {
                            //and if the item is not a periodical,
//                            if (strstr(strtolower($item->collection), "periodicals") == false) {
//                                //set HTML code for reserve button
//                                $item->docnum = "<a href='" . $this->config->item('reserve_urlA') . $docnum . $this->config->item('reserve_urlB') . $this->config->item('reserve_url_itemseq') . $this->config->item('reserve_urlC') .
//                                        "' target='_blank'/>" .
//                                        "<button class='reserveBtn'>Reserve</button></a>";
//                                //but if due date is set to 'On Shelf', yet loan-status is not 'Normal Loan',
//                                //*Note: Fulfills library's requirement of "Do not hide items with Item Status: Normal which are currently ‘on shelf’."
//                                if (strstr(strtolower($item->due_date), "on shelf") == true && strstr(strtolower($item_data->{'loan-status'}), "normal") == false) {
//                                    $item->docnum = ""; //remove code to hide reserve button
//                                }
//                            }
//                            //set HTML for locator button
//                            //if(strstr($item->loan_status, "AV") == false)
////                            {
////                                $item->locator = "<input type='button' name='locateBtn' id='availFloorPlanButton' value='View Floor Plan' />";
////                            }
////                            else
////                            {
////                                $item->locator = "";
////                            }
//
////                            $item->locator = "<button name='locateBtn' class='reserveBtn' value='View Floor Plan'>View Floor Plan</button>";

                            //$item->locator = "<button name='locateBtn' id='availFloorPlanButton'>View Floor Plan</button>";


                        } else {
                            //if no status records are found for item, set to "" to hide reserve and locator button
                            $item->docnum = "";
                            $item->locator = "";
                        }
                        //add item to array
                        $item_datas[] = $item;
                        $count_item++;
                    }//close loadNum if 
                    $count_total++;
                }
            }//close foreach
        }
        $count = 0;
        
        /*Section to generate HTML 'templates' for avaiability status records*/
        
        //if there is at least one item parsed in previous section
        if ($count_total > 0) {
            //loop through array
            foreach ($item_datas as $entry) {
                
                //continue looping to generate 'templates' if count is less than the display limit
                if ($count < $this->config->item('displayNum')) {
                    
                    //for first item
//                    if ($count == 0) {
                        //use a different set of HTML code
//                        $html_str .= $this->config->item('html_1s');
                        //Set item location and collection to first item in list.
                        //*Note: For shelf locator purpose. Locator will always display
                        //location of first item on list
//                        $item->location = $entry->location;
//                        $item->collection = $entry->collection;
//                    } else {
                        //use standard set of HTML code for second item onwards
                        $html_str .= $this->config->item('html_1');
//                    }
                    $temp_loan_str = "";
                    if (strlen($entry->loan_status) >= 15 && $entry->loan_status != "No Hard Copies Available") {
                                //set loan-status into item as it is
                                $temp_loan_str = (string) substr($entry->loan_status, 0, 15). "...";
                            }
                            else {
                                //else crop the characters from position 0 to 15, and append "..." to the end
                                //this is to prevent long loan-status messages from breaking formatting/styling
                                $temp_loan_str = $entry->loan_status;
                                        
                            }
                    
                    
                    //Form 'template' by lacing item's variables with HTML tags(retrieved from config/config.php)
                    //@Config: Availability model static html data
                            
                    
                    $collectionString = $entry->collection;
                    if(strlen($collectionString) >= 15){
                        if(strstr($collectionString, "Level")){
                            $collectionString = str_replace("Level", "Lv", $collectionString);
                        }
                    }
                    $html_str .= $entry->barcode
                            . $this->config->item('html_2')
                            . $temp_loan_str . $this->config->item('html_2')
                            . $entry->sub_library . $this->config->item('html_2')
                            . $collectionString . $this->config->item('html_3')
                            . $entry->due_date . $this->config->item('html_4')
                            . $entry->due_time . $this->config->item('html_5')
                            //."</div><div class='miniWrap' id='aBtm'>test</div>"."</div>" //code for fourth div for buttons
                            
                            ;
                    //Yi Le added a <div class='availButtons'> to align reserve and locator icons to the right
                    $html_str .= "</div><div class='availButtons'>";
                    // Yi Le's code to append a shelf locator button for each availability record's item
                    $collection = $entry->collection;
                    $location = $entry->location;
                    if(stristr($collection, "Materials") === false){
                        $html_str .= "<div class='miniWrap' id='aBtmB'>" . "<button name='eachlocateBtn' class='x-button eachBtnLocator x-button-plain' value='" . $collection . "_" . $location . "'></button>";
                    }
                    else{
                        $html_str .= "<div class='miniWrap' id='aBtmB'>" . "<button name='eachdisablelocateBtn' class='x-button eachDisableBtnLocator x-button-plain'></button>";
                    }
                    
                    
                    $in_check = false;
                    //if (strstr(strtolower($item_data->{'loan-status'}), strtolower($filter))) {
                    
                    foreach ($this->config->item('reserveTerms') as $filter) {
                        if (strstr(strtolower($entry->loan_status), strtolower($filter)))
                        {
                            $in_check = true;
                            break;
                        }
                        else
                        {
                            $in_check = false;
                        }
                    }
                    //*Note: Fulfills library's requirement of "Do not hide items with Item Status: Normal which are currently ‘on shelf’."
                    //if (strstr(strtolower($item->due_date), "on shelf") == true && strstr(strtolower($item_data->{'loan-status'}), "normal") == false) {
                    if(($entry->due_time!="-"&&$in_check)||(strstr(strtolower($entry->due_date), "on shelf")&&strstr(strtolower($entry->loan_status), strtolower("Normal Loan"))))
                    {
                        $tempItem = $seq_items[$entry->barcode];
                        if($tempItem["on_hold"]=="N"&&$tempItem["requested"]=="N")
                        {
                            $recKey = substr($tempItem["rec_key"], -6, 6);
                            $url = $this->config->item('reserve_urlA') . $docnum . $this->config->item('reserve_urlB') . $recKey . $this->config->item('reserve_urlC');
                            $html_str .= $this->config->item('reserve_htmlA') . "<a href='". $url. "' target='_blank'/>" . $this->config->item('reserve_htmlB');
                            //$item->docnum = $this->config->item('reserve_urlA') . $docnum . $this->config->item('reserve_urlB') . $this->config->item('reserve_url_itemseq') . $this->config->item('reserve_urlC') .
                                        
                                        
                        }
                    }
                    else
                    {
                        //Yi Le added a </div> to close <div class='availButtons'> to align reserve and locator buttons
                        $html_str .= "</div></div></div>";
                    }
                    
                    $count++;

                } else {
                    //hit display limit, break loop
                    break;
                }
            }
            //For items with more than one availability status,
            //Add button link to library catalogue to facilate viewing of more records
            //and reservation of items other than the first(item_sequence 00010).
            if ($count > 1) {

                $html_str .= $this->config->item('html_end1a') . $count . " of " . $count_total . $this->config->item('html_end1b') . $this->config->item('html_end2') . $docnum . $this->config->item('html_end3');
            }
        }//close if (total_count>0)
        else {
            //XML has item records, but none passed filter
            
            //Load default values to item
            $item->loan_status = "No Copies Available";
            $item->due_date = "-";
            $item->due_time = "-";
            $item->sub_library = "-";
            $item->collection = "-";
            $item->barcode = "-";
            //Generate template with default values
            //@Config: Availability model static html data
            $html_str .= $this->config->item('html_1s') . $item->barcode
                    . $this->config->item('html_2')
                    . $item->loan_status . $this->config->item('html_2')
                    . $item->sub_library . $this->config->item('html_2')
                    . $item->collection . $this->config->item('html_3')
                    . $item->due_date . $this->config->item('html_4')
                    . $item->due_time . $this->config->item('html_5');
        }

        //set html string to item, add item to itemDataList array and return
        $item->html = $html_str;
        $itemDataList = array('Availability' => $item);
        return $itemDataList;
        //return $seq_items;
    }
    //Utility function to check if a field is blank (@author : Timothy Cheung)
    function blankCheck($item_Data) {
        if ($item_Data != "") {
            return (string) $item_Data;
        } else {
            return "-";
        }
    }

}

?>
